package com.gitee.srurl.core.factory.handle;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.gitee.srurl.core.annotation.Order;
import com.gitee.srurl.core.api.IDomainSelector;
import com.gitee.srurl.core.api.IUniqueIdGenerate;
import com.gitee.srurl.core.config.ShortUrlConfig;
import com.gitee.srurl.core.dto.request.GenerateShortUrlDTO;
import com.gitee.srurl.core.factory.ShortUrlFactory;
import com.gitee.srurl.core.util.NumberUtil;
import com.gitee.srurl.core.util.UrlUtil;
import org.springframework.stereotype.Component;

import java.net.URI;

/**
 * @author zxw
 * @date 2023/4/29 8:21
 */
@Component
@Order(3)
public class UniqueGenerateHandle implements IGenerateShortUrlHandle {

    @Override
    public boolean handle(GenerateShortUrlDTO generateShortUrlDTO) {

        ShortUrlConfig shortUrlConfig = ShortUrlFactory.getShortUrlConfig();
        IUniqueIdGenerate idGenerate = shortUrlConfig.getIdGenerate();
        long id = idGenerate.getId();
        String shortId = NumberUtil.encode10To62(id);

        IDomainSelector domainSelector = shortUrlConfig.getDomainSelector();
        URI host = URLUtil.getHost(UrlUtil.parse(generateShortUrlDTO.getOriginUrl()));
        if (host == null) {
            generateShortUrlDTO.setMsg("url解析失败");
            generateShortUrlDTO.setSuccess(false);
            return false;
        }
        String domain = domainSelector.selector(host.toString());
        String shortUrl = StrUtil.format("{}/{}", domain, shortId);
        generateShortUrlDTO.setShortUrl(shortUrl);
        generateShortUrlDTO.setShortUrlDomain(domain);
        generateShortUrlDTO.setShortKey(shortId);

        return true;
    }
}

